﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using MySql.Data.MySqlClient;
using DateBaseConnectionPool;

namespace TestMySqlConnetPoll
{
    public class SysLogTable
    {
        #region 变量定义 系统日志记录
        public class objSystemLog
        {
            public DateTime DtTime;
            public string logText = "";
        }
        private objDate ValueDay = new objDate();   //日志的天，换天清除缓冲区
        public Dictionary<string, List<objSystemLog>> ValueList = new Dictionary<string, List<objSystemLog>>();
        public int ErrorFlag = 0;
        public bool ReadyValueList = false;

        struct threadObj
        {
           public objDate t;
           public int type;
        }
        #endregion
        private Mutex keyMutex = new Mutex();
        static private int keykey = 0;
        
        #region 系统日志记录
        public bool InsertTable(string LogTypeName, string LogText)
        {
            string TableName = "systemlogtable";
            int LogType = c_Device.GetSysLogID(LogTypeName);
            if (LogType == -1)
            {
                ErrorFlag = 1;
                return false;      //类型不正确
            }
            
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorFlag = 3;
                    return false;
                }
                if (con != null)
                {
                    StringBuilder InsertStatement = new StringBuilder();
                    InsertStatement.Append(string.Format("insert into {0}(type,logText) ", TableName));
                    InsertStatement.Append(" values(?type,?logText)");
                    MySqlCommand InsertCommand = new MySqlCommand(InsertStatement.ToString(), con);
                    InsertCommand.Parameters.Add(new MySqlParameter("?type", MySqlDbType.Byte)).Value = LogType;
                    InsertCommand.Parameters.Add(new MySqlParameter("?logText", MySqlDbType.VarChar, 1024)).Value = LogText;

                    try
                    {
                        int k = InsertCommand.ExecuteNonQuery();
                        if (k == 1)
                        {
                        }
                        else
                        {
                            ErrorFlag = 4;
                        }
                    }
                    catch (MySqlException e)
                    {
                        //写异常日记
                        ErrorFlag = 5;
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        ErrorFlag = 6;
                    }
                }
            }
            return (ErrorFlag == 0);
        }

        public void ReadValueList(objDate date, string LogTypeName)
        {
            ErrorFlag = 0;
            ReadyValueList = false;
            if (date.year != ValueDay.year || date.month != ValueDay.month || date.day != ValueDay.day)
            {
                ValueDay = date;
                ValueList.Clear();
            }
            if (ValueList.ContainsKey(LogTypeName))
            {
                ReadyValueList = true;
                return;
            }
            int LogType = c_Device.GetSysLogID(LogTypeName);
            if (LogType == -1) ErrorFlag = 1;
            else
            {
                threadObj obj = new threadObj();
                obj.t = date;
                obj.type = LogType;
                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadReadValueList), obj);
            }
        }


        private void ThreadReadValueList(object o)
        {
            threadObj obj = (threadObj)o;
            string TableName = "systemlogtable";
            objDate date = obj.t;
            int logType = obj.type;

            string StartTimeStamp = string.Format("'{0}-{1}-{2} 00:00:00'", date.year, date.month, date.day);
            string EndTimeStamp = string.Format("'{0}-{1}-{2} 23:59:59'", date.year, date.month, date.day);

            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorFlag = 3;
                }
                if (con != null)
                {
                    StringBuilder SelectStatement = new StringBuilder();

                    SelectStatement.Append(string.Format("select DtTime,logText from {0} where DtTime >={1} and DtTime <={2} and type = {3}", TableName, StartTimeStamp, EndTimeStamp, logType));

                    try
                    {
                        MySqlCommand selectCommand = new MySqlCommand(SelectStatement.ToString(), con);
                        selectCommand.CommandTimeout = 120;   //120s操作超时

                        MySqlDataReader read = selectCommand.ExecuteReader();
                        List<objSystemLog> k = new List<objSystemLog>();
                        while (read.Read())
                        {
                            objSystemLog t = new objSystemLog();
                            t.DtTime = read.GetDateTime(read.GetOrdinal("DtTime"));

                            if (!read.IsDBNull(read.GetOrdinal("logText")))
                            {
                                t.logText = read.GetString(read.GetOrdinal("logText"));
                            }
                            k.Add(t);
                        }
                        read.Close();
                        string KeyName = c_Device.GetSysLogTypeName(obj.type);

                        if (KeyName != "")
                        {
                            ValueList.Add(KeyName, k);
                            ReadyValueList = true;
                        }
                        else
                        {
                            ErrorFlag = 3;
                        }
                    }
                    catch (MySqlException e)
                    {
                        //写错误日志
                        ErrorFlag = 4;
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        //写错误日志
                        ErrorFlag = 5;
                    }
                }
                else ErrorFlag = 6;
            }
            else ErrorFlag = 7;
        }
        #endregion
    }
}
